package com.bootcamp.s2_0922.ds.Exercise._0929_Ex;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Objects;

/**
 * @program: myClassCode
 * @description:
 * @author: Keyu Li
 * @create: 2021-09-29 20:16
 **/

public class Ex1_CollectionDelSame {
    public static void main(String[] args) {
        // 假设不含有 null 元素
        Collection<User> users = new ArrayList<>(10);
        users.add(new User("ws001",1));
        users.add(new User("ws002",2));
        users.add(new User("ws003",3));
        users.add(new User("ws004",4));
        users.add(new User("ws001",1));
        users.add(new User("ws001",1));
        users.add(new User("ws002",2));
        users.add(new User("ws003",3));
        User userTemp = new User("old",100);
        users.add(userTemp);
        users.add(userTemp);
        users.add(userTemp);

        System.out.println(users);
        System.out.println("-------------------");

        // 获取 iterator 对象
        Iterator<User> iterator = users.iterator();
        // 临时存储遍历的user到新的集合中
        Collection<User> tempUsers = new ArrayList<>(10);
        while (iterator.hasNext()){
            User userIter = iterator.next();
            // ArrayList的 contains()使用了 User重写的 equals方法。
            if (!tempUsers.contains(userIter)){
                tempUsers.add(userIter);
                continue;
            }else {
                // 如果包含，则删除当前元素
                iterator.remove();
            }
        }
        System.out.println(users);
    }
}

class User{
    String name;
    int age;

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof User)) return false;
        User user = (User) o;
        return age == user.age &&
                Objects.equals(name, user.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }

    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer("User{");
        sb.append("name='").append(name).append('\'');
        sb.append(", age=").append(age);
        sb.append('}');
        return sb.toString();
    }
}
